import { useMemo, useEffect, useState } from 'react';
import dayjs from 'dayjs';

interface PromotionConfig {
  startDate: string;
  endDate: string;
  discountRates: Record<number, number>;
  bonusMonths: Record<number, number>;
}

interface PackageItem {
  year: number;
  title: string;
  originalPrice: number;
  popular?: boolean;
  features?: string[];
}

interface UsePromotionOptions {
  config: PromotionConfig;
  packages: PackageItem[];
}

interface UsePromotionReturn {
  isPromotionActive: boolean;
  remainingDays: number;
  packages: Array<PackageItem & { amount: number; actualYear: number }>;
  getBonusText: (year: number) => string;
  getPromotionText: () => string;
}

/**
 * 促销管理自定义Hook
 * @param options 促销配置选项
 * @returns 促销状态和相关方法
 */
export const usePromotion = ({
  config,
  packages: basePackages,
}: UsePromotionOptions): UsePromotionReturn => {
  const [, forceUpdate] = useState(0);

  // 检查是否在促销期间
  const isPromotionActive = useMemo(() => {
    const now = dayjs();
    const start = dayjs(config.startDate);
    const end = dayjs(config.endDate).endOf('day');
    return now.isAfter(start) && now.isBefore(end);
  }, [config.startDate, config.endDate]);

  // 计算剩余天数
  const remainingDays = useMemo(() => {
    if (!isPromotionActive) return 0;
    const now = dayjs();
    const end = dayjs(config.endDate).endOf('day');
    return Math.max(0, end.diff(now, 'day'));
  }, [isPromotionActive, config.endDate]);

  // 动态生成套餐数据
  const packages = useMemo(() => {
    return basePackages.map((pkg) => {
      // 计算实际年限：原年限 + 加送月数转换的年限
      const bonusMonths = isPromotionActive
        ? config.bonusMonths[pkg.year] || 0
        : 0;
      const bonusYears = bonusMonths / 12; // 将月数转换为年数
      const actualYear = pkg.year + bonusYears;

      return {
        ...pkg,
        amount: isPromotionActive
          ? Math.round(
              pkg.originalPrice * (config.discountRates[pkg.year] || 1),
            )
          : pkg.originalPrice,
        actualYear, // 实际年限（包含加送时间）
      };
    });
  }, [
    basePackages,
    isPromotionActive,
    config.discountRates,
    config.bonusMonths,
  ]);

  // 获取加送文案
  const getBonusText = (year: number): string => {
    if (!isPromotionActive) return '';
    const bonusMonths = config.bonusMonths[year];
    if (!bonusMonths) return '';

    if (bonusMonths >= 12) {
      const years = Math.floor(bonusMonths / 12);
      const months = bonusMonths % 12;
      if (months === 0) {
        return `再加送${years}年`;
      } else {
        return `再加送${years}年${months}个月`;
      }
    } else {
      return `再加送${bonusMonths}个月`;
    }
  };

  // 获取促销文案
  const getPromotionText = (): string => {
    if (!isPromotionActive) return '';

    const bonusTexts = Object.entries(config.bonusMonths).map(
      ([year, months]) => {
        if (months >= 12) {
          const years = Math.floor(months / 12);
          const remainingMonths = months % 12;
          if (remainingMonths === 0) {
            return `买${year}年加送${years}年`;
          } else {
            return `买${year}年加送${years}年${remainingMonths}个月`;
          }
        } else {
          return `买${year}年加送${months}个月`;
        }
      },
    );

    return `${config.endDate}日之前${bonusTexts.join('，')}！`;
  };

  // 定时更新剩余天数
  useEffect(() => {
    if (!isPromotionActive) return;

    const timer = setInterval(() => {
      // 强制更新组件以重新计算剩余天数
      forceUpdate((prev) => prev + 1);
    }, 60000); // 每分钟更新一次

    return () => clearInterval(timer);
  }, [isPromotionActive]);

  return {
    isPromotionActive,
    remainingDays,
    packages,
    getBonusText,
    getPromotionText,
  };
};

export default usePromotion;
